package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.entity.SysUser;
import com.example.service.ISysLoginService;
import com.example.utils.Constant;
import com.example.utils.JwtUtil;
import com.example.utils.R;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.concurrent.TimeUnit;

@Service
public class SysLoginServiceImpl implements ISysLoginService {

    private static Logger logger = LoggerFactory.getLogger(SysLoginServiceImpl.class);

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private Dao dao;

    @Override
    public R login(String username, String password,String ip) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        SysUser sysUser = dao.fetch(SysUser.class, Cnd.where("username", "=", username));
        if (null == sysUser) {
            return R.error("不存在该用户");
        }
        if (!password.equals(sysUser.getPassword())) {
            return R.error("账号或密码不对");
        }
        String subject = JSON.toJSONString(sysUser);
        String token = JwtUtil.createToken(String.valueOf(sysUser.getId()), ip, subject, Constant.TOKEN_KEY);
        String key = "token:" + sysUser.getId();
        redisTemplate.opsForValue().set(key, token);
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        R r = new R();
        r.put("token", token);
        return r;
    }

}
